package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

var wait = sync.WaitGroup{}

// 取消协程
func main() {
	t1 := time.Now()
	ctx, cancel := context.WithCancel(context.Background())
	wait.Add(1)
	go func() {
		ip, err := getIp(ctx)
		fmt.Println(ip, err)
		//wait.Done()
	}()
	go func() {
		time.Sleep(time.Second * 5)
		cancel()
	}()
	wait.Wait()
	fmt.Println("执行完成", time.Since(t1))

}

func getIp(ctx context.Context) (ip string, err error) {
	go func() {
		select {
		case <-ctx.Done():
			err = ctx.Err()
			fmt.Println("协程取消", err)
			wait.Done()
			return
		}
	}()
	time.Sleep(time.Second * 3)
	ip = "192.168.47.135"
	wait.Done()
	return
}
